import { extractTokenFromHeader, getUserFromToken } from './jwt'

/**
 * 验证用户身份并返回用户信息
 * @param event - Nuxt事件对象
 * @returns 用户信息
 */
export async function requireAuth(event: any) {
  // 获取Authorization请求头
  const authHeader = getHeader(event, 'authorization')
  
  // 提取token
  const token = extractTokenFromHeader(authHeader)
  
  if (!token) {
    throw createError({
      statusCode: 401,
      statusMessage: 'Unauthorized',
      data: { message: '未提供认证token' }
    })
  }

  // 验证token并获取用户信息
  const user = await getUserFromToken(token)
  
  if (!user) {
    throw createError({
      statusCode: 401,
      statusMessage: 'Unauthorized',
      data: { message: '无效的token或用户不存在' }
    })
  }

  return user
}
